<template>
<!-- 体检风险规则组件 -->
  <div>
    <el-table
      :data="tableData"
      style="width: 100%" 
      height="505px"
      ref="multipleTable"
      highlight-current-row
      border
      header-cell-class-name="table-header-class">
      <el-table-column
        label="风险因子"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.physicalExamination" placeholder="请选择" filterable clearable @change="projectCategoryChange(scope.row)" :disabled="pageDisabled">
            <el-option
              v-for="item in projectCategoryDic"
              :key="item.id + ''"
              :label="item.projectName"
              :value="item.id + ''">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="体检项目"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.physicalExaminationDetailsId" placeholder="请选择" filterable clearable @change="projectNameChange(scope.row)" :disabled="pageDisabled">
            <el-option
              v-for="item in getProNameDic(scope.row)"
              :key="item.id + ''"
              :label="item.projectName"
              :value="item.id + ''">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="检查结果(非描述型)"
        align='center'
        width="180">
        <template slot-scope="scope" v-if="!scope.row._updataFlag">
          <el-select v-model="scope.row.measuringResult" placeholder="请选择" :loading="scope.row._measuringResultFlag" filterable clearable v-if="scope.row.type == '1'" :disabled="pageDisabled" @visible-change="measuringResultChange($event,scope.$index, scope.row)" @change="measuringChange($event,scope.$index, scope.row)">
            <el-option
              v-for="item in measuringResultDic[scope.$index]"
              :key="item.id"
              :label="item.referenceIntervalFirst"
              :value="item.id + ''">
            </el-option>
          </el-select>
          <el-tooltip :disabled="!scope.row.measuringResult" v-else-if="scope.row.type == '2'" effect="dark" :content="handleResult(scope.row.measuringResult)" placement="top">
            <span :class="['result-item',{'disabled-item': pageDisabled}]" @click="measuringResultClick(scope.row,'体检项对象.测量结果')">{{handleResult(scope.row.measuringResult)}}</span>
          </el-tooltip>
          <el-input v-else-if="scope.row.type == '3'" disabled></el-input>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column
        label="检查结果(描述型1)"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.commonProperty" placeholder="请选择" :loading="scope.row._commonPropertyFlag" :disabled="scope.row.type != '3' || pageDisabled" filterable clearable @visible-change="commonPropertyChange($event,scope.$index, scope.row)" @change="comPropertyChange(scope.row)">
            <el-option
              v-for="item in commonPropertyDic[scope.$index]"
              :key="item.id"
              :label="item.propertyName"
              :value="item.id + ''">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="检查结果(描述型2)"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.propertyType" placeholder="请选择" :loading="scope.row._propertyTypeFlag" :disabled="scope.row.type != '3' || pageDisabled || !scope.row.commonProperty" filterable clearable @visible-change="propertyChange($event,scope.$index, scope.row)">
            <el-option
              v-for="item in propertyDic[scope.$index]"
              :key="item.id"
              :label="item.propertyType"
              :value="item.id + ''">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="风险因子标志"
        align='center'
        width="350">
        <template slot-scope="scope">
          <el-input v-model="scope.row.hitMark" disabled></el-input>
        </template>
      </el-table-column>
      <el-table-column
        label="评点对象.评分项"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.scoringItems" :precision="0" placeholder="请输入" :disabled="pageDisabled"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        label="评点对象.累加标记"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.scoringItemsTag" placeholder="请选择" clearable :disabled="pageDisabled">
            <el-option
              v-for="item in yesOrNoDic"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" align='center' width="150" fixed="right" v-if="!pageDisabled">
        <template slot-scope="scope">
          <div style="display:flex;justify-content: center;">
            <span class="handle-btn" @click="handleAdd(scope.$index, scope.row)">新增</span>
            <span class="handle-btn" @click="handleDel(scope.$index, scope.row)">删除</span>
            <span class="handle-btn" @click="handleCopy(scope.$index, scope.row)">复制</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <!-- 新增疾病规则弹窗 -->
    <el-dialog
      v-if="conditionVisible"
      title="配置条件"
      :visible.sync="conditionVisible"
      :close-on-click-modal="false"
      width="850px"
      center>
      <conditionRelation ref="conditionRelation" :tableTitle="tableTitle" source="physical" :logicDic="logicDic" @saveRelation="()=>{conditionVisible = false}"></conditionRelation>
    </el-dialog>
  </div>
</template>

<script>
  import conditionRelation from "./conditionRelation";

  import constant from '@/utils/constant';
  import {
    getPhysicalRiskRuleApi,
    getMeasurementResultTypeApi,
    getMeasurementResultTypeOneApi,
    getMeasurementUnitApi,
    getDiseaseEntityAttributeApi,
    getAttributeSortApi
  } from "@/api/medicalLibrary/examProjectLibrary";

  export default {
    components: {
	  	conditionRelation
	  },
    props: {
      projectCategoryDic: {
        type: Array,
        default: ()=>{
          return []
        }
      },
      projectNameDic: {
        type: Array,
        default: ()=>{
          return []
        }
      },
      logicDic: {
        type: Array,
        default: ()=>{
          return []
        }
      },
      pageDisabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        yesOrNoDic: [{value: '0', label: '否'},{value: '1', label: '是'}],  //是否字典表 
        commonPropertyDic: [], //属性枚举值
        propertyDic: [],  //属性分类枚举值
        measuringResultDic: [],  //测量结果枚举值
        tableData: [],
        ruleGroupVersionId: '',  //版本id

        // 弹窗
        conditionVisible: false,
        tableTitle: '',  //表头名称
      }
    },
    methods: {
      // 获取疾病的体检风险规则
      getRiskRule(diseaseID,version){
        this.$store.dispatch('loading/CHANGE_LOADING',true)
        this.tableData = []
        this.commonPropertyDic = [] //属性枚举值
        this.propertyDic = []  //属性分类枚举值
        this.measuringResultDic = []  //测量结果枚举值
        getPhysicalRiskRuleApi({diseaseID,version}).then(res => {
					this.$store.dispatch('loading/CHANGE_LOADING',false)
					if (res.resultCode == constant.SUCCESS) {
						this.tableData = res.data || []

            let coverFlag = true
            if(!this.tableData.length) {
              if(!this.pageDisabled) this.handleAdd(-1)
            }
            else {
              this.ruleGroupVersionId = res.data[0].ruleGroupVersionId
              coverFlag = false
              this.tableData.forEach((item,index)=>{
                if(!item.scoringItems && item.scoringItems!==0) item.scoringItems = undefined
                if(!item.commonProperty) this.$set(item,'commonProperty','')
                if(!item.propertyType) this.$set(item,'propertyType','')
                if(item.type == '1') this.measuringResultDic[index] = item.measuringResult && item.measuringResultName ? [{id: item.measuringResult, referenceIntervalFirst: item.measuringResultName}] : []
                if(item.type == '3') {
                  this.commonPropertyDic[index] = item.commonProperty && item.commonPropertyName ? [{id: item.commonProperty, propertyName: item.commonPropertyName}] : []
                  this.propertyDic[index] = item.propertyType && item.propertyTypeName ? [{id: item.propertyType, propertyType: item.propertyTypeName}] : []
                }
              })
            }
            this.$emit('getCoverFlag',coverFlag,this.ruleGroupVersionId)
					}
				}).catch(err => {
					this.$store.dispatch('loading/CHANGE_LOADING',false);
				});
      },
      
      // 点击测量结果
      measuringResultClick(row,tableTitle){
        if(this.pageDisabled) return
        this.tableTitle = tableTitle
        this.conditionVisible = true
        setTimeout(()=>{
          // 根据项目名称获取单位
          this.$refs.conditionRelation.getMeasurementUnit(getMeasurementUnitApi,{id:row.physicalExaminationDetailsId})
          // 处理配置条件列表数据
          this.$refs.conditionRelation.currentRow = row
          this.$refs.conditionRelation.handleRelation('measuringResult')
        })
      },
      // 动态获取项目名称的下拉列表值
      getProNameDic(row){
        if(!row.physicalExamination) return []
        else {
          let filterArr = this.projectNameDic.filter(item=>item.parent == row.physicalExamination)
          return filterArr
        }
      },
      // 项目大类改变时触发
      projectCategoryChange(row){
        row.physicalExaminationDetailsId = ''
        this.restRowData(row)
      },
      // 项目名称改变时触发
      projectNameChange(row){
        this.$set(row,'_updataFlag',true)
        this.restRowData(row)
        if(row.physicalExaminationDetailsId) this.getMeasurementResult(row)
      },
      // 病症实体-属性改变时触发
      comPropertyChange(row){
        row.propertyType = ''
      },
      // 清空规则配置行
      restRowData(row){
        row.measuringResult = ''
        row.commonProperty = ''
        row.propertyType = ''
        row.hitMark = ''
        row.scoringItems = undefined
        row.scoringItemsTag = ''
        row.type = '99'
      },
      // 获取测量结果类型
      getMeasurementResult(row){
        getMeasurementResultTypeApi({codeId: row.physicalExaminationDetailsId}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
            this.$set(row,'type',res.data.type)
            this.$set(row,'_updataFlag',false)
					}
				})
      },
      // 测量结果下拉框获得焦点时触发
      measuringResultChange(event,_index,row){
        this.$set(row,'_measuringResultFlag',true)
        if(event && row.physicalExaminationDetailsId){
          getMeasurementResultTypeOneApi(row.physicalExaminationDetailsId).then(res => {
            if (res.resultCode == constant.SUCCESS) {
              this.$set(this.measuringResultDic,[_index],res.data)
            }
            this.$set(row,'_measuringResultFlag',false)
          })
        }
      },
      // 测量结果下拉框发生改变时触发
      measuringChange(event,_index,row){
        if(event) row.measuringResultName = this.measuringResultDic[_index].filter(fItem=>fItem.id == event)[0].referenceIntervalFirst
        else row.measuringResultName = ''
      },
      // 病症实体.属性下拉框获得焦点时触发
      commonPropertyChange(event,_index,row){
        this.$set(row,'_commonPropertyFlag',true)
        if(event && row.physicalExaminationDetailsId){
          getDiseaseEntityAttributeApi({id: row.physicalExaminationDetailsId}).then(res => {
            if (res.resultCode == constant.SUCCESS) {
              this.$set(this.commonPropertyDic,[_index],res.data)
            }
            this.$set(row,'_commonPropertyFlag',false)
          })
        }
      },
      // 病症实体.属性分类下拉框获得焦点时触发
      propertyChange(event,_index,row){
        this.$set(row,'_propertyTypeFlag',true)
        if(event && row.commonProperty){
          getAttributeSortApi({id: row.commonProperty}).then(res => {
            if (res.resultCode == constant.SUCCESS) {
              this.$set(this.propertyDic,[_index],res.data)
            }
            this.$set(row,'_propertyTypeFlag',false)
          })
        }
      },
      // 处理测量结果的显示
      handleResult(measuringResult){
        let result = measuringResult
        if(result) {
          result = result.replace(/\^/g, '').replace(/#/g, '').replace(/\$/g, '').replace(/\("/g, '').replace(/\"\)/g, '')
        }
        return result
      },
      /* ----列表操作按钮 */
      // 添加
      handleAdd(index, row) {
        let obj = {
          physicalExamination: '',
          physicalExaminationDetailsId: '',
          measuringResult: '',
          commonProperty: '',
          propertyType: '',
          hitMark: '',
          scoringItems: undefined,
          scoringItemsTag: '',
          type: '99'
        }
        this.tableData.push(obj)
        this.measuringResultDic.push([])
        this.commonPropertyDic.push([])
        this.propertyDic.push([])
        /* this.tableData.splice(index+1,0,obj)
        this.measuringResultDic.splice(index+1,0,[])
        this.commonPropertyDic.splice(index+1,0,[])
        this.propertyDic.splice(index+1,0,[]) */
      },
      // 删除
      handleDel(index, row) {
        this.tableData.splice(index,1)
        this.measuringResultDic.splice(index,1)
        this.commonPropertyDic.splice(index,1)
        this.propertyDic.splice(index,1)
        if(!this.tableData.length) this.handleAdd(-1)
      },
      // 复制
      handleCopy(index, row) {
        let obj = JSON.parse(JSON.stringify(row))
        delete obj.id
        delete obj.hitMark
        this.tableData.push(obj)
        this.measuringResultDic.push(this.measuringResultDic[index] ? JSON.parse(JSON.stringify(this.measuringResultDic[index])) : [])
        this.commonPropertyDic.push(this.commonPropertyDic[index] ? JSON.parse(JSON.stringify(this.commonPropertyDic[index])) : [])
        this.propertyDic.push(this.propertyDic[index] ? JSON.parse(JSON.stringify(this.propertyDic[index])) : [])

        /* this.tableData.splice(index+1,0,obj)
        this.measuringResultDic.splice(index+1,0,this.measuringResultDic[index] ? JSON.parse(JSON.stringify(this.measuringResultDic[index])) : [])
        this.commonPropertyDic.splice(index+1,0,this.commonPropertyDic[index] ? JSON.parse(JSON.stringify(this.commonPropertyDic[index])) : [])
        this.propertyDic.splice(index+1,0,this.propertyDic[index] ? JSON.parse(JSON.stringify(this.propertyDic[index])) : []) */
      },
      // 处理保存的数据
      saveHandle(){
        let physicalRiskRuleFieds = ['physicalExamination','physicalExaminationDetailsId','measuringResult','commonProperty','propertyType','hitMark','scoringItems','scoringItemsTag'],
        flag = true
        let filterArr = JSON.parse(JSON.stringify(this.tableData))
        filterArr.forEach(fItem=>{
          let itemFlag = false
          if(this.ruleGroupVersionId) fItem.ruleGroupVersionId = this.ruleGroupVersionId
          if(!fItem.scoringItems && fItem.scoringItems !== 0) fItem.scoringItems = ''
          
          physicalRiskRuleFieds.forEach(item=>{
            if(fItem[item] || fItem[item] === 0) itemFlag = true
          })
          if(!itemFlag) flag = false
        })
        return {
          flag,
          filterArr
        }
      }
    }
  }
</script>
<style lang="less" scoped>
.handle-btn{
  cursor: pointer;
  color: #409eff;
  display: inline-block;
  padding: 0 8px;
}

.result-item{
  color: #40a9fd;
  cursor: pointer;
  width: 100%;
  display: inline-block;
  height: 24px;
  line-height: 30px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.disabled-item{
  color: #606266;
  cursor: no-drop;
}
/deep/ .el-input-number__decrease,/deep/ .el-input-number__increase{
  display: none;
}
</style>